<?php
/**
 * @Name: AuthToken.php
 * @Author: yashuai
 * @Time 2020/6/3 10:32
 */

namespace App\Http\Middleware;

use Closure;
use App\Http\Model\ConstCode;
use Illuminate\Http\Request;
use App\Http\Model\Rbac\UserModel;
use App\Http\Logic\Rbac\UserTokenLogic;

class AuthToken
{

    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     * @author yashuai
     * @Time 2020/6/6 10:33
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('token');
        //  token 验证
        $userId = UserTokenLogic::instance()->id($token);
        if ($userId === false) {
            _throw(107000);
        }

        $userInfo = UserModel::getInfo($userId, 'UserID', ['IsSuper', 'UserStatus']);
        if (empty($userInfo) || $userInfo['UserStatus'] != ConstCode::BASIC_STATUS_NORMAL) {
            _throw(107000, '登录异常：当前用户不存在');
        }
        // 权限验证
        $power = UserTokenLogic::instance([
            'UserID' => $userId,
            'Event'  => implode('.', _controller_action()),
            'User'   => $userInfo
        ])->validatorNodePower();
        if ($power !== true) {
            _throw(107004, implode('.', _controller_action()));
        }
        $request->userId = $userId;

//        $request->userId = 1;
        return $next($request);
    }


}


